﻿using LPBToolsLib;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 电子票存档工具
{
    public partial class FEBillQuery : Form
    {
        SQLSerConfig DBServerCFG { get; }
        SQLSerHelper tSQLRun { get; }

        int iPageRecCount = 50;

        const string sPageInfoMask = "共{0}页 当前页：";

        public FEBillQuery(SQLSerConfig DestDBServerCFG)
        {
            InitializeComponent();
            DBServerCFG = DestDBServerCFG;
            tSQLRun=new SQLSerHelper(DBServerCFG); 
            dataGridViewResult.AutoGenerateColumns = false;
            //dataGridViewResult.RowHeadersWidth = dataGridViewResult.RowHeadersWidth + 10;
            ResetAll();
        }
        private void ResetAll(int iKey = 0)
        {
            if (iKey == 0)
            {
                textBoxEIid.Text = string.Empty;
                textBoxotalTaxAm.Text = string.Empty;
                textBoxSellerIdNum.Text = string.Empty;
                textBoxSellerName.Text = string.Empty;
                textBoxTotalAmWithoutTax.Text = string.Empty;
                comboBoxInIssuType.SelectedIndex = -1;
                comboBoxTaxpayerType.SelectedIndex = -1;
                comboBoxGeneralOrSpecialVAT.SelectedIndex = -1;
                dateTimePickerEnd.Value = DateTime.Now;
                dataGridViewResult.DataSource = null;
                comboBoxPageRecCount.SelectedIndex = 2;
                iPageRecCount = 50;
                labelRecInfo.Text= string.Empty;
                comboBoxPageIdx.SelectedIndex = -1;
                comboBoxPageIdx.Items.Clear();
                comboBoxPageIdx.Visible = false;
                TSStatusLabelRecCount.Text= string.Empty;
            }
        }

        private void buttonReset_Click(object sender, EventArgs e)
        {
            ResetAll();
        }


        string getQuerySQL(out string QueryCountSQL)
        {
            QueryCountSQL = "";
            string strSQL = @"
  SELECT count(*)
  FROM [HCEBills].[dbo].[ElecBills]
  where EIid is not null
                ";
             
            if (!string.IsNullOrEmpty(textBoxEIid.Text))
                strSQL += " and EIid like '%" + textBoxEIid.Text + "%'";
            if (!string.IsNullOrEmpty(textBoxSellerIdNum.Text))
                strSQL += " and SellerIdNum like '%" + textBoxSellerIdNum.Text + "%'";
            if (!string.IsNullOrEmpty(textBoxSellerName.Text))
                strSQL += " and SellerName like '%" + textBoxSellerName.Text + "%'";
            float iTmp = 0;
            if (!string.IsNullOrEmpty(textBoxotalTaxAm.Text))
            {
                if (float.TryParse(textBoxotalTaxAm.Text, out iTmp))
                    strSQL += " and TotalTaxAm =" + iTmp.ToString("0.00");
                else
                {
                    MessageBox.Show("输入内容无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBoxotalTaxAm.Text = "";
                }
            }
            if (!string.IsNullOrEmpty(textBoxTotalAmWithoutTax.Text))
            {
                if (float.TryParse(textBoxTotalAmWithoutTax.Text, out iTmp))
                    strSQL += " and TotalAmWithoutTax =" + iTmp.ToString("0.00");
                else
                {
                    MessageBox.Show("输入内容无效！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    textBoxTotalAmWithoutTax.Text = "";
                }
            }
            if (comboBoxInIssuType.SelectedIndex >= 0)
                strSQL += " and InIssuType =" + (comboBoxInIssuType.SelectedIndex ).ToString();
            if (comboBoxGeneralOrSpecialVAT.SelectedIndex >= 0)
                strSQL += " and GeneralOrSpecialVAT =" + (comboBoxGeneralOrSpecialVAT.SelectedIndex + 1).ToString();
            if (comboBoxTaxpayerType.SelectedIndex >= 0)
                strSQL += " and TaxpayerType =" + (comboBoxTaxpayerType.SelectedIndex + 1).ToString();

            strSQL += " and IssueTime>'" + dateTimePickerStar.Value.ToString("yyyy-MM-dd") + "'";
            strSQL += " and IssueTime<='" + dateTimePickerEnd.Value.ToString("yyyy-MM-dd") + "'";

            QueryCountSQL = strSQL;
            strSQL = strSQL.Replace("count(*)" ,@"
	            [EIid] as '票据编号'
                ,case [InIssuType] when 0 then '红字发票' when 1 then '蓝字发票' end as '票据类型'
                ,case [EInvoiceType] when 0 then '未知错误' when 1 then '电子发票'  when 2 then '纸质发票' end as '出票方式'
                ,case [GeneralOrSpecialVAT] when 0 then '未知错误' when 1 then '专用发票'  when 2 then '普通发票' end as '增值税类型'
                ,case [TaxpayerType] when 0 then '未知错误' when 1 then '一般'  when 2 then '小规模' end as '纳税人类型'
                ,[SellerIdNum] as '销售方纳税识别号'
                ,[SellerName] as '销售方名称'
                ,[SellerBankName] as '销售方开户行'
                ,[SellerBankAccNum] as '销售方账户'
                ,[BuyerIdNum] as '购买方纳税识别号'
                ,[BuyerName] as '购买方名称'
                ,[IssueTime] as '开票日期'
                ,[TotalAmWithoutTax] as '无税金额'
                ,[TotalTaxAm] as '税额'
                ,[TotalAmount] as '价税合计'
                ,[TaxBureauCode]
                ,[TaxBureauName]
                ,[ElecBill]
                ,[CreateTime]
                 ");

            strSQL += "order by IssueTime desc";

            return strSQL;
        }


        void QueryRunSQL(int iDestPageIdx = 0)
        {
            string QueryCountSQL = "";
            string strSQL = getQuerySQL(out QueryCountSQL);
            if (!string.IsNullOrEmpty(strSQL))
            {
                int iRecCount = 0;
                object tRCount = tSQLRun.runSelect(QueryCountSQL);
                int.TryParse(tRCount.ToString(), out iRecCount);
                int iTBCount = 0;
                dataGridViewResult.DataSource = tSQLRun.runSelect(strSQL, out iTBCount, iDestPageIdx, iPageRecCount);
                TSStatusLabelRecCount.Text = "记录数：" + iRecCount.ToString();
                int iPageTotel = 0;
                if (iPageRecCount != 0)
                    iPageTotel = iRecCount / iPageRecCount;
                if (iPageTotel <= 0)
                    iPageTotel += 1;
                if ((iRecCount % iPageRecCount)>0)
                    iPageTotel += 1;
                labelRecInfo.Text = string.Format(sPageInfoMask, iPageTotel.ToString());
                onChangePageIdxList = true;
                try
                {
                    comboBoxPageIdx.Visible = true;
                    comboBoxPageIdx.Items.Clear();
                    for (int i = 0; i < iPageTotel; i++)
                        comboBoxPageIdx.Items.Add((i + 1).ToString());
                    comboBoxPageIdx.SelectedIndex = 0;
                }
                finally
                {
                    onChangePageIdxList = false;
                }
            }
        }
        bool onChangePageIdxList = false;

        int QueryRunSQL(out DataTable tDResult)
        {
            tDResult = null;
            int iRecCount = 0;
            string QueryCountSQL = "";
            string strSQL = getQuerySQL(out QueryCountSQL);
            if (!string.IsNullOrEmpty(strSQL))
            {
                tDResult = tSQLRun.runSelect(strSQL, out iRecCount);
                
            }
            return (tDResult != null) ? iRecCount : -1;
        }

        private bool checkInput()
        {
            bool iResult = true;
            float iTmp = 0;
            if ((!string.IsNullOrEmpty(textBoxotalTaxAm.Text))
                && (!float.TryParse(textBoxotalTaxAm.Text, out iTmp)))
            {
                iResult = false;
                MessageBox.Show("金额输入错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if ((!string.IsNullOrEmpty(textBoxTotalAmWithoutTax.Text))
                && (!float.TryParse(textBoxTotalAmWithoutTax.Text, out iTmp)))
            {
                iResult = false;
                MessageBox.Show("金额输入错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return iResult;
        }

        private void buttonQuery_Click(object sender, EventArgs e)
        {
            QueryRunSQL();
        }

        private void comboBoxPageRecCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (comboBoxPageRecCount.SelectedIndex)
            {
                case 0:
                    iPageRecCount = 10;
                    break;
                case 1:
                    iPageRecCount = 30;
                    break;
                case 3:
                    iPageRecCount = 100;
                    break;
                default:
                    iPageRecCount = 50;
                    break;
            }
        }

        private void ToolStripMenuItem_导入票据_Click(object sender, EventArgs e)
        {

        }

        private void buttonUploadEBills_Click(object sender, EventArgs e)
        {
            FUploadEBills tUploadEBills = new FUploadEBills(DBServerCFG);
            tUploadEBills.ShowDialog();
        }

        private void ToolStripMenuItem全部导出_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("如果数据量较大时，需要较长时间，请耐心等待！","警告",MessageBoxButtons.YesNo,MessageBoxIcon.Warning)== DialogResult.Yes)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    tDEBillDir = folderBrowserDialog1.SelectedPath + "\\";
                    if (Directory.Exists(tDEBillDir))
                    {

                        int iRecCount = QueryRunSQL(out tDEBillResult);
                        if (iRecCount > 0)
                        {
                            tProgressBar = new FProgressBar("正在下载电子票据", iRecCount);
                            tDEBillThd = new Thread(downloadEBillsthd);
                            tDEBillThd.Start();
                            tProgressBar.ShowDialog();
                            MessageBox.Show(string.Format("成功导出{0}条电子票据！" + iRecCount.ToString()));
                        }
                    }
                }
            }
            /*
           
            */
        }

        DataTable tDEBillResult = null;
        string tDEBillDir = "";

        Thread tDEBillThd = null;
        FProgressBar tProgressBar = null;
        void downloadEBillsthd()
        {
            if (tDEBillResult != null)
                try
                {
                    foreach (DataRow row in tDEBillResult.Rows)
                    {
                        string sEBCode = row["票据编号"].ToString() + ".xml";
                        string sEBXML = row["ElecBill"].ToString();
                        if (!File.Exists(tDEBillDir + sEBCode))
                        {
                            File.WriteAllText(tDEBillDir + sEBCode, sEBXML, Encoding.UTF8);
                        }
                        if (tProgressBar != null)
                        {
                            tProgressBar.RunCount += 1;
                        }
                        Thread.Sleep(500);
                    }
                }
                finally
                {
                    tDEBillThd = null;
                    tDEBillResult = null;
                    tDEBillDir = "";
                    if (tProgressBar!=null)
                        tProgressBar.needClose = true;
                }
        }

        /// <summary>
        /// 如果没有查询记录时，无法展开菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void contextMenuStrip2_Opening(object sender, CancelEventArgs e)
        {
            if (dataGridViewResult.SelectedRows.Count <= 0)
                e.Cancel = true;
        }

        private void ToolStripMenuItem导出当前记录_Click(object sender, EventArgs e)
        {
            if (dataGridViewResult.SelectedRows.Count > 0)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    string tDEBDir = folderBrowserDialog1.SelectedPath + "\\";
                    if (Directory.Exists(tDEBDir))
                    {
                        string sEBCode = dataGridViewResult.SelectedRows[0].Cells[0].Value.ToString()+".xml";
                        string sEBXML = dataGridViewResult.SelectedRows[0].Cells[11].Value.ToString();
                        if (!File.Exists(tDEBDir + sEBCode))
                        {
                            File.WriteAllText(tDEBDir + sEBCode, sEBXML, Encoding.UTF8);
                        }
                        if (File.Exists(tDEBDir + sEBCode))
                            MessageBox.Show("成功导出1条电子票据！");
                    }
                }
            }
        }

        private void comboBoxPageIdx_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!onChangePageIdxList)
                QueryRunSQL(comboBoxPageIdx.SelectedIndex+1);
        }

        private void dataGridViewResult_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            if (dataGridViewResult.Rows.Count > 0)
            {
                using (SolidBrush b = new SolidBrush(e.RowIndex == dataGridViewResult.CurrentRow.Index ? Color.Red : dataGridViewResult.RowHeadersDefaultCellStyle.ForeColor))
                {
                    e.Graphics.DrawString((Convert.ToInt32(e.RowIndex) + 1).ToString(System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 5, e.RowBounds.Location.Y + 4);
                }
            }
        }
    }
}
